/**
 * @author changke
 */
var dndDropbox, dndPreview;
dndDropbox = $("#dndDropbox").get(0);
dndPreview = $("#dndPreview").get(0);

var dndAllowDrop = true;
var dndJustUploaded = false;
var dndImageCount = 0;

function handleFiles(files) {
	for(var i = 0; i < files.length; i++) {
		var file = files[i];
		var imageType = /image.*/;
		
		if(!file.type.match(imageType)) {
			continue;
		}
	
		var img = document.createElement("img");
		img.classList.add("dndPrv");
		img.file = file;
		dndPreview.appendChild(img);
		
		var reader = new FileReader();
		reader.onloadend = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
		reader.readAsDataURL(file);
	}
}

function clearDropped() {
	// remove all children
	while(dndPreview.firstChild) {
		dndPreview.removeChild(dndPreview.firstChild);
	}
	dndAllowDrop = true;
	dndJustUploaded = false;
	dndImageCount = 0;
}

function allUploaded() {
	$("#dndPreview .prvImageFN").css("display", "block");
	$("#dndPreview .prvImageFN").mouseover(function() {
		$(this).select();
	});
	dndJustUploaded = true;
}

function sendFiles() {
	if(dndJustUploaded) {
		return;
	}
	var imgs = document.querySelectorAll(".dndPrv");
	dndImageCount = imgs.length;
	for(var i = 0; i < imgs.length; i++) {
		new FileUpload(imgs[i], imgs[i].file);
	}
	dndAllowDrop = false;
}

function FileUpload(img, file) {
	this.ctrl = createThrobber(img);
	var xhr = new XMLHttpRequest();
	this.xhr = xhr;

	var self = this;
	this.xhr.upload.addEventListener("progress", function(e) {
		if(e.lengthComputable) {
			var percentage = Math.round((e.loaded * 100) / e.total);
			self.ctrl.update(percentage);
		}
	}, false);

	xhr.upload.addEventListener("load", function(e) {
		self.ctrl.update(100);
		var canvas = self.ctrl.ctx.canvas;
		canvas.parentNode.removeChild(canvas);
	}, false);
	
	xhr.onreadystatechange = function(ev) {
		if(xhr.readyState == 4) {
			if(xhr.status == 200) {
				var resJsonString = xhr.responseText;
				var resJson = JSON.parse(resJsonString);
				$(img).after("<input type=\"text\" class=\"prvImageFN\" value=\"[img]" + g_uploadedImagePathPrefix + resJson.pix + "[/img]\" />");
				dndImageCount--;
				if(dndImageCount <= 0) {
					allUploaded();
				}
			}
		}
	};
	
	var imageJsonObj = {
		"filename": file.name,
		"filedata": img.getAttribute("src"),
		"filetype": file.type
	};
	
	var imageJsonString = JSON.stringify(imageJsonObj);

	xhr.open("POST", g_userSiteRoot + "/mgmt/upload_pix_dnd");
	xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
	xhr.sendAsBinary(imageJsonString);
}

function dragenter(ev) {
	ev.stopPropagation();
	ev.preventDefault();
	$(ev.target).addClass("draghover");
}

function dragover(ev) {
	ev.stopPropagation();  
	ev.preventDefault();
}

function dragleave(ev) {
	ev.stopPropagation();  
	ev.preventDefault();
	$(ev.target).removeClass("draghover");
}

function drop(e) {
	e.stopPropagation();
	e.preventDefault();
	
	if(dndAllowDrop) {
		var dt = e.dataTransfer;
		var files = dt.files;
		
		handleFiles(files);
	}
}

function createThrobber(img) {
	var x = img.x;
	var y = img.y;

	var canvas = document.createElement("canvas");
	dndPreview.appendChild(canvas);
	
	canvas.width = img.width;
	canvas.height = img.height;
	var size = Math.min(canvas.height, canvas.width);
	canvas.style.top = y + "px";
	canvas.style.left = x + "px";
	canvas.classList.add("throbber");
	var ctx = canvas.getContext("2d");
	ctx.textBaseline = "middle";
	ctx.textAlign = "center";
	ctx.font = "14px monospace";
	ctx.shadowOffsetX = 0;
	ctx.shadowOffsetY = 0;
	ctx.shadowBlur = 14;
	ctx.shadowColor = "white";

	var ctrl = {};
	ctrl.ctx = ctx;
	ctrl.update = function(percentage) {
		var ctx = this.ctx;
		ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
		ctx.fillStyle = "rgba(0, 0, 0, " + (0.8 - 0.8 * percentage / 100)+ ")";
		ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
		ctx.beginPath();
		ctx.arc(ctx.canvas.width / 2, ctx.canvas.height / 2, size / 6, 0, Math.PI * 2, false);
		ctx.strokeStyle = "rgba(255, 255, 255, 1)";
		ctx.lineWidth = size / 10 + 4;
		ctx.stroke();
		ctx.beginPath();
		ctx.arc(ctx.canvas.width / 2, ctx.canvas.height / 2, size / 6, -Math.PI / 2, (Math.PI * 2) * (percentage / 100) + -Math.PI / 2, false);
		ctx.strokeStyle = "rgba(0, 0, 0, 1)";
		ctx.lineWidth = size / 10;
		ctx.stroke();
		ctx.fillStyle = "white";
		ctx.baseLine = "middle";
		ctx.textAlign = "center";
		ctx.font = "11px monospace";
		ctx.fillText(percentage + "%", ctx.canvas.width / 2, ctx.canvas.height / 2);
	}
	ctrl.update(0);
	return ctrl;
}
